//
//  LGWeibopicture.swift
//  我的微博
//
//  Created by ming on 16/10/15.
//  Copyright © 2016年 ming. All rights reserved.
//

import UIKit


//微博配图xib
class LGWeibopicture: UIView {
    //计算单张图的size
    var status:LGWeiBoStatus?{
        didSet{
           
           scanleSize()
            
        }
        
    }
    
    private func scanleSize(){
        
        //更改第0张图片的size
        let viewSize = status?.pictureSize ?? CGSize()
        if status?.picUrlS?.count == 1 {
              let imageV = subviews[0]
            let rect = CGRect(x: 0, y: WeiBoStatusPicOuterMargin, width: viewSize.width, height: viewSize.height - WeiBoStatusPicOuterMargin)
            imageV.frame = rect
            
        }else{
            //当不是大于一张图片的时候，就改回原来的
            let imageV = subviews[0]
            let rect = CGRect(x: 0, y: WeiBoStatusPicOuterMargin, width: WeiBoPicItemWidth, height:WeiBoPicItemWidth)
            imageV.frame = rect
            
        }
      
        
        
         picturBottom.constant = status?.pictureSize.height ?? 0
    }
    
    
    var model:[LGWeiBoPicModel]?{
        
        didSet{
            
            for v in subviews{
                v.isHidden = true
                
            }
            var index = 0;
            for url in model ?? [] {
                
            let v = subviews[index] as! UIImageView
           
                if model?.count == 4 && index == 1 {
                    index += 1
                }
            
 
            v.lg_setImage(urlSting: url.thumbnail_pic, placeholderImage: nil)

                 v.isHidden = false
                index += 1
                
            }
            
            
            
            
            
        }
        
        
    }
    
    
     @IBOutlet weak var picturBottom: NSLayoutConstraint!
    
    override func awakeFromNib() {
        super.awakeFromNib()
         backgroundColor = superview?.backgroundColor
      
        setUI()
    }
   
    
}
extension LGWeibopicture{
    
    
    //循环添加imageView
   func setUI(){
   
    
    let count = 3
  
    let rect = CGRect(x: 0, y: WeiBoStatusPicOuterMargin, width: WeiBoPicItemWidth, height: WeiBoPicItemWidth)
    
    
    for i in 0..<count * count {
        clipsToBounds = true
        
        let imageV = UIImageView()
         imageV.contentMode = .scaleAspectFill
        imageV.clipsToBounds = true
        imageV.backgroundColor = UIColor.red
        //计算frame
        let row = CGFloat(i / count)
        let lin = CGFloat(i % count)
        let xoffset = lin * (WeiBoPicItemWidth + WeiBoinnerMargin)
        let yoffset = row * (WeiBoPicItemWidth + WeiBoinnerMargin)
        
        imageV.frame = rect.offsetBy(dx: xoffset , dy: yoffset)

        addSubview(imageV)
        
        
    }
    
    
    
    
    
    
        
        
        
        
    }
    
    
    
    
}
